package com.example.autopia.model.Repositories

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.autopia.model.Item.Car
import com.example.autopia.model.Item.Card
import com.example.autopia.model.Item.News
import com.example.autopia.model.Item.User
import com.example.autopia.utilities.KEY_BD_USERS
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlin.coroutines.suspendCoroutine


class UsersRepository {
    private val database = FirebaseDatabase.getInstance()
    private var reference = database.getReference(KEY_BD_USERS)

    fun addUser(id: String, email: String, name: String = "Ваше имя", password: String): Boolean {
        val user = User(id, email, password, name = name, balance = 0, photo = "null")
        var status = false
        reference.child(id).setValue(user)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun changePhoto(userId: String, photo: String): Boolean {
        var status = false
        reference.child(userId).child("photo").setValue(photo)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun changeName(userId: String, name: String): Boolean {
        var status = false
        reference.child(userId).child("name").setValue(name)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun changeEmail(userId: String, email: String): Boolean {
        var status = false
        reference.child(userId).child("email").setValue(email)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun changePassword(userId: String, password: String): Boolean {
        var status = false
        reference.child(userId).child("password").setValue(password)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun addCar(userId: String, car: Car): Boolean {
        var status = false
        reference.child(userId).child("carList").child(car.number).setValue(car)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun changeCarColor(userId: String, carNumber: String, color: String): Boolean {
        var status = false
        reference.child(userId).child("carList").child(carNumber).child("color").setValue(color)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun deleteCar(userId: String, carNumber: String): Boolean {
        var status = false
        reference.child(userId).child("carList").child(carNumber).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun addCard(userId: String, card: Card): Boolean {
        var status = false
        reference.child(userId).child("cardList").child(card.number).setValue(card)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun deleteCard(userId: String, cardNumber: String): Boolean {
        var status = false
        reference.child(userId).child("cardList").child(cardNumber).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun addYoursNews(userId: String, newsId: String): Boolean {
        var status = false
        reference.child(userId).child("yourNewsList").child(newsId).setValue(newsId)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->

            }
        return status
    }

    fun removeYourNews(userId: String,  newsId: String): Boolean {
        var status = false
        reference.child(userId).child("yourNewsList").child(newsId).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun addLikesNews(userId: String, likesNewsId: String): Boolean {
        var status = false
        reference.child(userId).child("likesNewsList").child(likesNewsId).setValue(likesNewsId)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->

            }
        return status
    }

    fun removeLikesNews(userId: String, likesNewsId: String): Boolean {
        var status = false
        reference.child(userId).child("likesNewsList").child(likesNewsId).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun getAllItems() : MutableLiveData<ArrayList<User>> {
        val itemsList = ArrayList<User>()
        val result = MutableLiveData<ArrayList<User>>()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children) {
                    val id = itemSnapshot.child("id").value.toString()
                    val email = itemSnapshot.child("email").value.toString()
                    val password = itemSnapshot.child("password").value.toString()
                    val name = itemSnapshot.child("name").value.toString()
                    val photo = itemSnapshot.child("photo").value.toString()
                    var verificated = 0
                    if (itemSnapshot.child("verificated").value!=null){
                        verificated = itemSnapshot.child("verificated").value.toString().toInt()
                    }
                    var admin = 0
                    if (itemSnapshot.child("admin").value!=null){
                        admin = itemSnapshot.child("admin").value.toString().toInt()
                    }
                    var balance = 0
                    if (itemSnapshot.child("balance").value!=null){
                        balance = itemSnapshot.child("balance").value.toString().toInt()
                    }
                    val carsList = ArrayList<Car>()
                    for (cars in itemSnapshot.child("carList").children){
                        val model = cars.child("model").value.toString()
                        val number = cars.child("number").value.toString()
                        val color = cars.child("color").value.toString()
                        val viewtype =0
                        val car = Car(model,number,color,viewtype)
                        carsList.add(car)
                    }

                    val cardList = ArrayList<Card>()
                    for (cards in itemSnapshot.child("cardList").children){
                        val number = cards.child("number").value.toString()
                        val fio = cards.child("fio").value.toString()
                        val date = cards.child("date").value.toString()
                        val cvc =cards.child("cvc").value.toString().toInt()
                        val card = Card(number,fio, date, cvc)
                        cardList.add(card)
                    }

                    val yourNewsList = ArrayList<String>()
                    for (news in itemSnapshot.child("yourNewsList").children){
                        val id = news.value.toString()
                        yourNewsList.add(id)
                    }

                    val likesNewsList = ArrayList<String>()
                    for (news in itemSnapshot.child("likesNewsList").children){
                        val id = news.value.toString()
                        likesNewsList.add(id)
                    }

                    val user = User(id,email,password, carsList, name, photo, cardList, yourNewsList, likesNewsList, verificated,balance,admin)
                    itemsList.add(user)
                }
                Log.d("Yatoro", "В списке пользователей " + itemsList.size.toString())
                result.value = itemsList
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro", "Ошибка в Users")
            }
        })
        return result
    }
    fun getUserById(id:String):MutableLiveData<User>{
        val user : MutableLiveData<User> = MutableLiveData()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val currentSnapshot = dataSnapshot.child(id)
                if (currentSnapshot.exists()) {
                    val id = currentSnapshot.child("id").value.toString()
                    val email = currentSnapshot.child("email").value.toString()
                    val password = currentSnapshot.child("password").value.toString()
                    val name = currentSnapshot.child("name").value.toString()
                    val photo = currentSnapshot.child("photo").value.toString()
                    var verificated = 0
                    if (currentSnapshot.child("verificated").value!=null){
                        verificated = currentSnapshot.child("verificated").value.toString().toInt()
                    }
                    var admin = 0
                    if (currentSnapshot.child("admin").value!=null){
                        admin = currentSnapshot.child("admin").value.toString().toInt()
                    }
                    var balance = 0
                    if (currentSnapshot.child("balance").value!=null){
                        balance = currentSnapshot.child("balance").value.toString().toInt()
                    }

                    val carsList = ArrayList<Car>()
                    for (cars in currentSnapshot.child("carList").children){
                        val model = cars.child("model").value.toString()
                        val number = cars.child("number").value.toString()
                        val color = cars.child("color").value.toString()
                        val viewtype =0
                        val car = Car(model,number,color,viewtype)
                        carsList.add(car)
                    }

                    val cardList = ArrayList<Card>()
                    for (cards in currentSnapshot.child("cardList").children){
                        val number = cards.child("number").value.toString()
                        val fio = cards.child("fio").value.toString()
                        val date = cards.child("date").value.toString()
                        val cvc =cards.child("cvc").value.toString().toInt()
                        val card = Card(number,fio, date, cvc)
                        cardList.add(card)
                    }

                    val yourNewsList = ArrayList<String>()
                    for (news in currentSnapshot.child("yourNewsList").children){
                        val id = news.value.toString()
                        yourNewsList.add(id)
                    }

                    val likesNewsList = ArrayList<String>()
                    for (news in currentSnapshot.child("likesNewsList").children){
                        val id = news.value.toString()
                        likesNewsList.add(id)
                    }
                    user.value = User(id,email,password, carsList, name, photo, cardList, yourNewsList, likesNewsList, verificated,balance,admin)

                } else {

                }
            }

            override fun onCancelled(databaseError: DatabaseError) {
                // Обработка ошибки
            }
        })
        return user
    }

    fun addBalance(userId: String, plus : Int): Boolean {
        var status = false
        reference.child(userId).child("balance").get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val newsData = task.result.value
                if (newsData != null) {
                    val currentBalance = newsData as Long
                    val updatedBalance = currentBalance + plus
                    reference.child(userId).child("balance").setValue(updatedBalance)
                    status = true
                }
            } else {
                Log.d("frikadelka", "error")
                // Обработайте ошибку, если операция завершилась неудачно
                val exception = task.exception
                if (exception != null) {
                    // Обработайте исключение
                }
            }
        }
        return status
    }
    fun removeBalance(userId: String, minus : Int): Boolean {
        var status = false
        reference.child(userId).child("balance").get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val newsData = task.result.value
                if (newsData != null) {
                    val currentBalance = newsData as Long
                    val updatedBalance = currentBalance - minus
                    reference.child(userId).child("balance").setValue(updatedBalance)
                    status = true
                }
            } else {
                // Обработайте ошибку, если операция завершилась неудачно
                val exception = task.exception
                if (exception != null) {
                    // Обработайте исключение
                }
            }
        }
        return status
    }
}